/**
 * Message Search Component
 * 
 * Global search functionality for messages with Ctrl+F shortcut
 */

import { useState, useEffect, useCallback } from 'react';
import { Search, X, ChevronUp, ChevronDown } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

export interface MessageSearchProps {
  isOpen: boolean;
  onClose: () => void;
  onSearch?: (query: string, currentIndex: number, totalMatches: number) => void;
}

export function MessageSearch({ isOpen, onClose, onSearch }: MessageSearchProps) {
  const [query, setQuery] = useState('');
  const [currentIndex, setCurrentIndex] = useState(0);
  const [totalMatches, setTotalMatches] = useState(0);

  // 搜索消息
  const performSearch = useCallback((searchQuery: string) => {
    if (!searchQuery.trim()) {
      setTotalMatches(0);
      setCurrentIndex(0);
      // 清除所有高亮
      clearHighlights();
      return;
    }

    // 获取所有消息内容
    const messageElements = document.querySelectorAll('[data-role="user"], [data-role="assistant"]');
    let matches = 0;
    const matchElements: Element[] = [];

    messageElements.forEach((element) => {
      const textContent = element.textContent || '';
      if (textContent.toLowerCase().includes(searchQuery.toLowerCase())) {
        matches++;
        matchElements.push(element);
        element.classList.add('message-search-match');
      } else {
        element.classList.remove('message-search-match', 'message-search-current');
      }
    });

    setTotalMatches(matches);
    if (matches > 0) {
      setCurrentIndex(1);
      highlightCurrent(0, matchElements);
    } else {
      setCurrentIndex(0);
    }

    onSearch?.(searchQuery, matches > 0 ? 1 : 0, matches);
  }, [onSearch]);

  // 高亮当前匹配项
  const highlightCurrent = (index: number, matchElements?: Element[]) => {
    const matches = matchElements || document.querySelectorAll('.message-search-match');
    matches.forEach((el, i) => {
      if (i === index) {
        el.classList.add('message-search-current');
        el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      } else {
        el.classList.remove('message-search-current');
      }
    });
  };

  // 清除所有高亮
  const clearHighlights = () => {
    document.querySelectorAll('.message-search-match, .message-search-current').forEach((el) => {
      el.classList.remove('message-search-match', 'message-search-current');
    });
  };

  // 下一个匹配
  const nextMatch = () => {
    if (totalMatches === 0) return;
    const newIndex = currentIndex >= totalMatches ? 1 : currentIndex + 1;
    setCurrentIndex(newIndex);
    highlightCurrent(newIndex - 1);
    onSearch?.(query, newIndex, totalMatches);
  };

  // 上一个匹配
  const previousMatch = () => {
    if (totalMatches === 0) return;
    const newIndex = currentIndex <= 1 ? totalMatches : currentIndex - 1;
    setCurrentIndex(newIndex);
    highlightCurrent(newIndex - 1);
    onSearch?.(query, newIndex, totalMatches);
  };

  // 处理输入变化
  const handleQueryChange = (value: string) => {
    setQuery(value);
    performSearch(value);
  };

  // 处理关闭
  const handleClose = () => {
    clearHighlights();
    setQuery('');
    setCurrentIndex(0);
    setTotalMatches(0);
    onClose();
  };

  // 键盘快捷键
  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        handleClose();
      } else if (e.key === 'Enter') {
        if (e.shiftKey) {
          previousMatch();
        } else {
          nextMatch();
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, query, currentIndex, totalMatches]);

  // 自动聚焦输入框
  useEffect(() => {
    if (isOpen) {
      const input = document.querySelector('#message-search-input') as HTMLInputElement;
      input?.focus();
    }
  }, [isOpen]);

  if (!isOpen) return null;

  return (
    <>
      {/* 添加搜索样式 */}
      <style>{`
        .message-search-match {
          background-color: rgba(255, 255, 0, 0.3);
          outline: 2px solid rgba(255, 255, 0, 0.5);
          outline-offset: 2px;
        }
        .message-search-current {
          background-color: rgba(255, 165, 0, 0.4);
          outline: 2px solid rgba(255, 165, 0, 0.8);
          outline-offset: 2px;
        }
      `}</style>

      {/* 搜索栏 */}
      <div className="fixed top-4 left-1/2 -translate-x-1/2 z-[100] bg-background border rounded-lg shadow-lg p-3">
        <div className="flex items-center gap-2 min-w-[400px]">
          <Search className="w-4 h-4 text-muted-foreground flex-shrink-0" />
          
          <Input
            id="message-search-input"
            type="text"
            placeholder="搜索消息... (Enter: 下一个, Shift+Enter: 上一个)"
            value={query}
            onChange={(e) => handleQueryChange(e.target.value)}
            className="flex-1 h-8 text-sm"
          />

          {totalMatches > 0 && (
            <div className="flex items-center gap-2 text-sm text-muted-foreground whitespace-nowrap">
              <span>
                {currentIndex} / {totalMatches}
              </span>
              <div className="flex gap-1">
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-7 w-7"
                  onClick={previousMatch}
                  disabled={totalMatches === 0}
                  title="上一个 (Shift+Enter)"
                >
                  <ChevronUp className="w-4 h-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-7 w-7"
                  onClick={nextMatch}
                  disabled={totalMatches === 0}
                  title="下一个 (Enter)"
                >
                  <ChevronDown className="w-4 h-4" />
                </Button>
              </div>
            </div>
          )}

          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7 flex-shrink-0"
            onClick={handleClose}
            title="关闭 (Esc)"
          >
            <X className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </>
  );
}

